<template>
   <div class="all-wrap" >
    <div class="all-title">角色管理</div>
    <div class="top-controllers" style="margin-bottom: 4px;">
      <el-input
        v-model="searchValue"
        clearable
        class="w-50 m-2"
        placeholder="请输入用户名"
      />
      <el-button type="primary" @click="searchClick">搜索</el-button>
      <el-button type="primary" @click="addRoleFn">新增</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="roleName" label="roleName"  />
      <el-table-column prop="description" label="description" />
      
      <el-table-column label="auth" >
        <template  #default="scope">
          <el-tag v-for="(item,index) in scope.row.auths" :key="index">{{item.authName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Controllers" width="280">
        <template  #default="scope">
          <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
          <el-button type="primary" size="small" @click="editAuth(scope.row)">编辑权限</el-button>
          <el-popconfirm
            width="220"
            confirm-button-text="OK"
            cancel-button-text="No, Thanks"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="Are you sure to delete this?"
            @confirm="confirmEvent(scope.row)"
          >
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <br/>
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="10"
      layout="total, prev, pager, next"
      :total="dataTotal"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogFormVisible" :title="dialogState">
      <el-form :model="form" ref="ruleFormRef" label-width="100" :rules="rules">
        <el-form-item label="角色名"  prop="role_name">
          <el-input v-model="form.role_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="介绍" props="description">
          <el-input v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogAuth" title="修改权限">
      <el-select v-model="authArr" multiple placeholder="Select" style="width: 100%">
        <el-option v-for="item in authsOptions" :key="item.id" :label="item.authName" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitEdit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onBeforeMount} from 'vue';
import {ElMessage, FormInstance}from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import {getRoleList,addRole,editRole,deleteRole,editRoleAuth} from '../apis/role'
import {getAuth} from '../apis/auth'
interface option {
  id:number
  authName:string
}

let searchValue=ref('')
let tableData=ref([])
let currentPage=ref(1)
let dataTotal=ref(0)
let dialogFormVisible=ref(false)
let dialogState=ref('新增数据')
let editId=ref(0)
let dialogAuth=ref(false)
let authArr=ref([])
let authsOptions=ref<option[]>([])
let form=reactive({
  role_name:'',
  description:''
})
const ruleFormRef = ref<FormInstance>()
let rules=reactive({
  role_name:[
    {required:true,message:"角色名称必填",trigger:"blur"},
    {min:2,max:8,message:"名称长度2-8"}
  ],
  description:[{required:false},]
})

const editAuth=(row)=>{
  editId.value=row.id
  dialogAuth.value=true
  authArr.value=row.auths.map(e=>e.id)
}
const cancelEdit=()=>{
  editId.value=0
  dialogAuth.value=false
  authArr.value=[]
}
const submitEdit=async()=>{
  let params={
    id:editId.value,
    authId:authArr.value.join(",")
  }
  let res=await editRoleAuth(params)
  if(res.status==200){
    ElMessage({
      message: '修改角色权限成功',
      type: 'success',
    })
    getData()
    dialogAuth.value=false
    cancelEdit()
  }
}
const resetForm=()=>{
  let empty={}
  for(let i in form){
    empty[i]=''
  }
  Object.assign(form,empty)
}
const searchClick=()=>{
  currentPage.value=1
  getData()
}
const addRoleFn=()=>{
  dialogFormVisible.value=true
}
const editData=(parmas)=>{
  dialogState.value="修改数据"
  editId.value=parmas.id
  dialogFormVisible.value=true
  form=reactive({
    "role_name":parmas.roleName,
    "description":parmas.description
  })
}
const confirmEvent=async(row)=>{
  let res=await deleteRole({id:row.id})
  if(res.status==200){
    ElMessage({
      message: '删除角色成功',
      type: 'success',
    })
    getData()
  }
}
const handleCurrentChange=()=>{
  getData()
}
const cancel=(ruleFormRef)=>{
  dialogFormVisible.value=false
  resetForm()
}
const submit=async(formEl)=>{
  await formEl.validate(async(valid, fields) => {
    if(valid){
      if(dialogState.value=='新增数据'){
        let res=await addRole(form)
        if(res.status==200){
          ElMessage({
            message: '新增角色成功',
            type: 'success',
          })
          dialogFormVisible.value=false
          getData()
          resetForm()
        }
      }else{
        let res=await editRole({
          id:editId.value,
          ...form
        })
        if(res.status==200){
          ElMessage({
            message: '修改角色成功',
            type: 'success',
          })
          dialogFormVisible.value=false
          getData()
          resetForm()
        }
      }
    }else{
      console.log(fields)
    }
  })
}
const getData=async()=>{
  let parmas={
    "role_name":searchValue.value.trim(),
    "page": currentPage.value,
  }
  let res=await getRoleList(parmas)
  if (res.status==200){
    tableData.value=res.data.data
    dataTotal.value=res.data.total
  }
}
onBeforeMount(()=>{
  getData()
  getAuth({page:1,pageSize:99}).then(res=>{
    if (res.status==200){
      authsOptions.value=res.data.data
    }
  })
})
</script>
<style lang="less" scoped>
.top-controllers{
  width: 100%;
  height: 30px;
  .w-50{
    width: 200px;
    margin-right: 20px;
  }
}

</style>